(function($){
	var KEY = "jforest.upload";
	
	var SelectPanel = function(options){
		this.options = $.extend({
			bindObj:null,
			rootPath:'',
			ajax:{},
			imgDblClick:function(item){}
		},options);
		var opts=this.options;
		//this.ajax = jf.getAjax($.extend({},opts.ajax));
		this.createEl();
	}

	SelectPanel.prototype = {
		createEl:function(){
			this.$el = $('<div class="modal fade" tabindex="-1"><div class="modal-dialog">'
				+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button>'
				+'<h4 class="modal-title">选择图片</h4></div><div class="modal-body clearfix"><ul class="imgSelectList"></ul></div>');
			$('body').append(this.$el);
		},
		show:function(){
			var my=this,opts=this.options;
			this.ajax.load(function(result){
				if(opts.ajax.callback){
					result = opts.ajax.calback.apply(opts.bindObj || my,[result]);
				}
				if($.isArray(result)){
					var $ul = my.$el.find('.modal-body ul').empty();
					$.each(result,function(i,v){
						$('<li><img src="'+opts.rootPath+v.path+'" class="img-thumbnail"/><div>'+v.name+'</div></li>')
							.dblclick(function(){
								opts.imgDblClick.apply(opts.bindObj || my,[v]);
							}).appendTo($ul);
					});
				}
			})
			this.$el.modal('show');
		},
		hide:function(){
			this.$el.modal('hide');
		},
		clear:function(){
			this.$el.modal('hide');
			this.$el.remove();
		}
	}
	
	var Upload = function(element,options){
		this.$el = $(element);
		this.options = $.extend({
			url:null,
			paramName:'file',
			ajaxUpload:false,
			headers:{},
			data:{},
			selectAjax:null,
			ui:true,
			uploadStart:function(){},
			callback:function(result){
				this.$el.val(result.data);
			},
		},options);
		this.currPath=this.$el.val();
		var my=this,opts=this.options;
		if(opts.ui==true){this._createUi();}
	};

	Upload.prototype = {
		_createUi:function(){
			var my = this;
			var $div = this.$el.addClass('form-control').wrap('<div class="input-group"></div>').parent();
			var $span = $('<span class="input-group-btn"></span>').appendTo($div);
			if(this.options.selectAjax){
				$('<a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-search"></i></a>').appendTo($span).click(function(){my.select();});
			}
			$('<a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-upload"></i></a>').appendTo($span).click(function(){my.upload();});
		},
		_createUploadEl:function(){
			var my=this,opts=this.options;
			var targetName = '_ajax_upload_target' + Date.parse(new Date());
			var html = '<div style="display:none;">'
					+'<iframe name="'+targetName+'" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" style="display:none;"></iframe>'
					+'<form method="post" enctype="multipart/form-data" target="'+targetName+'" action="'+opts.url+'">'
					+'<input type="file" name="'+opts.paramName+'"/>';
			for (var key in opts.data) {
				html = html +'<input type="hidden" name="'+key+'" value="'+opts.data[key]+'"/>';
			};
			html = html +'</form></div>';

			this.$uploadEl = $(html).appendTo('body');
			this.$uploadEl.find('input[type="file"]').change(function(){
				opts.uploadStart.apply(my);
				if(opts.ajaxUpload){
					var formData = new FormData(my.$uploadEl.find('form')[0]);  
				    $.ajax({  
				          url: opts.url,  
				          type: 'POST',  
				          headers: opts.headers,
					  data: formData,  
				          async: false,  
				          cache: false,  
				          contentType: false,  
				          processData: false,  
				          success: function (result) {  
				        	  opts.callback.apply(my,[result]);
				          },  
				          error: function (returndata) { 
				        	  var result = {error:-1,msg:"上传文件失败，请稍后再试",data:returndata}
				        	  opts.callback.apply(my,[result]);
				          }  
				    });
				}else{
					my.$uploadEl.find('form').submit();
				}
			});
			this.$uploadEl.find('iframe').bind('load', function() {
				var doc = my._iframeDoc(this);
				var pre = doc.getElementsByTagName('pre')[0];
				var str = '';
				if(pre){str = pre.innerHTML;
				}else{str = doc.body.innerHTML;}
				try {
					var result = $.parseJSON(str);
					opts.callback.apply(my,[result]);
					my.$uploadEl.remove();
					my.$uploadEl = null;
				} catch (e) {}
			});
		},
		_iframeDoc:function(iframe) {
			return iframe.contentDocument || iframe.contentWindow.document;
		},
		select:function(){
			var opts=this.options;
			if(!this.selPanel && opts.selectAjax){
				this.selPanel = new SelectPanel({
					bindObj:this,
					ajax:opts.selectAjax,
					rootPath:opts.rootPath,
					imgDblClick:function(img){
						opts.callback.apply(this,[{data:img.path}]);
						this.selPanel.hide();
					}
				});
			}
			if(this.selPanel){this.selPanel.show();}else{
				//jf.error('不支持文件选择');
			}
		},
		getEl:function(){
			return this.$el;
		},
		upload:function(data){
			if(!this.$uploadEl){this._createUploadEl();}
			if(data){
				this.options.data = $.extend(this.options.data,data);
			}
			if(this.options.data){
			var $el = this.$uploadEl;
				$.each(this.options.data,function(k,v){
					 $el.find('input[name="'+k+'"]').val(v);
				});
			}
			this.$uploadEl.find('input[type="file"]').click();
		}
	};
	
	$.fn.jfUpload = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				value = new Upload(this,opts);//创建控件
				$this.data(KEY,value); 
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfUpload.Constructor = Upload;
	
})(window.jQuery)
